<template>
  <div class="alipay-config gray-box top-redius border-bottom-gray">
    <div class="title">
      {{ $t('sysManagement.sensitiveConfiguration') }}
    </div>
    <el-form
      ref="dataFormRef"
      label-width="5px"
      size="default"
      class="set-form"
      label-position="left"
      :rules="dataRule"
      :model="dataForm"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        style="width:500px"
        prop="sensitiveWord"
      >
        <el-alert
          :title="$t('sysManagement.sensitiveAlert')"
          type="warning"
          :closable="false"
          show-icon
        />
        <el-input
          v-model="dataForm.sensitiveWord"
          type="textarea"
          rows="28"
          :placeholder="$t('sysManagement.sensitiveWord')"
          controls-position="right"
          @input="inputLimit"
        />
      </el-form-item>

      <div
        class="default-btn"
        @click="onSubmit()"
      >
        {{ $t('sysManagement.save') }}
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const dataForm = ref({
  sensitiveWord: null
})
const dataFormRef = ref(null)
const dataRule = {
}
onMounted(() => {
  init()
})

const init = () => {
  nextTick(() => {
    http({
      url: http.adornUrl('/sys/pconfig/info/' + 'SENSITIVE_WORDS'),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      if (data) {
        dataForm.value = JSON.parse(data)
      }
    })
    dataFormRef.value?.resetFields()
  })
}
const inputLimit = (val) => {
  // 正则匹配非中英文及数字以及中文逗号的字符
  const reg = /[^\u4e00-\u9fa5\uff0c]/
  // 查找是否有非中英文及数字的字符
  // 没有则返回-1，有则返回对应位置
  const n = val.search(reg)
  if (n !== -1 || (val[val.length - 2] === '，' && val[val.length - 1] === '，')) {
    dataForm.value.sensitiveWord = val.slice(0, n)
  }
}
// 表单提交
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      dataForm.value.sensitiveWord = formatSensitiveWord(dataForm.value.sensitiveWord)
      http({
        url: http.adornUrl('/sys/pconfig/save'),
        method: 'post',
        data: http.adornData({
          paramKey: 'SENSITIVE_WORDS',
          paramValue: JSON.stringify(dataForm.value),
          remark: $t('sysManagement.sensitiveConfiguration')
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            emit('refreshDataList')
          }
        })
      })
    }
  })
}

/**
 * 删除重复、多余的中文逗号
 * @param str 敏感词配置
 * @returns {*}
 */
const formatSensitiveWord = (str) => {
  return str.replace(/，+/g, '，').replace(/，$/, '')
}

defineExpose({ init })
</script>
